<template>
    <rx-layout>

        <div slot="left" width="200" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="BPM"
                    :statisticConfig="statisticConfig"
                    read-key="task.read"
                    :edit="false"
                    @handSelect="handSelect"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :treeRootList="treeRootList"
                    :isBpmClient="isBpmClient"
                    :async="true">
                </rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center">
            <rx-fit :isheader="isheader">

                <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
                    <rx-list-title :title="i18n('list.taskManager','任务管理')"></rx-list-title>
                    <span class="search-btn-box" v-if="!isheader">
                        <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
                        {{$ti18('rxList.leachBtn','过滤')}}
                        </span>
                    </span>
                </div>

                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="searchbarClose">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">

                                <a-form-item :label="i18n('form.itemTitle','事项标题')">
                                    <a-input :placeholder="i18n('form.itemTitle','事项标题','input')"
                                             v-model="queryParam['Q_t.SUBJECT__S_LK']"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.taskStatus','任务状态')">
                                    <a-select :placeholder="i18n('form.taskStatus','任务状态','input')"
                                              v-model="queryParam['Q_t.STATUS__S_EQ']" :allowClear="true">
                                        <a-select-option value="UNHANDLE">
                                            {{i18n('form.waitToDo','待办')}}
                                        </a-select-option>
                                        <a-select-option value="HANDLE">
                                            {{i18n('form.processing','处理中')}}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="i18n('form.oddNumbers','单号')">
                                    <a-input :placeholder="i18n('form.oddNumbers','单号','input')"
                                             v-model="queryParam['Q_t.BILL_NO__S_EQ']"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="isheader">
                      <span class="table-page-search-submitButtons">
                        <a-button type="primary" icon="search" @click="search">
                            {{$ti18('rxList.searchBtn','查询')}}
                        </a-button>
                        <a-button style="margin-left: 4px" @click="cancel">
                            {{$ti18('rxList.resetBtn','重置')}}
                        </a-button>
                        <a @click="toggleAdvanced" style="margin-left: 8px">
                          {{ advanced ? '收起' : '展开' }}
                          <a-icon :type="advanced ? 'up' : 'down'"/>
                        </a>
                      </span>
                            </a-col>
                            <template v-if="advanced">
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.isThereAnExecutor','是否有执行人')">
                                        <a-select :placeholder="i18n('form.isThereAnExecutor','是否有执行人')"
                                                  v-model="queryParam['Q_t.EXECUTOR__S_EQ']" allowClear>
                                            <a-select-option value="1">
                                                {{i18n('executortMap.yes','有')}}
                                            </a-select-option>
                                            <a-select-option value="0">
                                                {{i18n('executortMap.no','无')}}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.taskOwner','任务所属人')">
                                        <rx-user-component :single="false" v-model="owner"></rx-user-component>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.taskExecutor','任务执行人')">
                                        <rx-user-component :single="false" v-model="assignee"></rx-user-component>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="colSpan">
                                    <a-form-item :label="i18n('form.timeFrom','任务创建时间')">
                                        <a-range-picker format="YYYY-MM-DD" @change="createTimeChange"/>
                                    </a-form-item>
                                </a-col>
                            </template>
                        </a-row>
                    </a-form>

                </div>

                <rx-grid
                    v-if="isShowManageTree"
                    ref="table"
                    :bordered="isBorder"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="20"
                    url="/api-bpm/bpm/core/bpmTask/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','20','30','40']"
                    id-field="taskId"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
          <span slot="subject" slot-scope="{text, record, index}">
            <a @click="handleTask(record)">{{record.subject}}</a>
          </span>
                    <span slot="status" slot-scope="{text, record, index}">
           <a-tag :color="statusMap[text].color">
              <span>{{statusMap[text].text}}</span>
            </a-tag>
          </span>
                    <span slot="assignee" slot-scope="{text, record}">
              <span>
                <a-tag v-for="taskExe in record.taskExecutors">
                    <a-icon v-if="taskExe.type=='group'" type="team"/>
                    <a-icon :type="taskExe.type"/>
                    &nbsp;{{taskExe.name}}</a-tag>
              </span>
          </span>
                    <span slot="appId" slot-scope="{ text, record }">
           {{allApps[text]?$i18(allApps[text].appName,'应用名称'):$ti18('rxList.noAppName','无')}}
         </span>
                    <span slot="action" slot-scope="{text, record }" class="actionIcons">
              <span @click.stop="handleTask(record)">
                  {{i18n('form.dealWith','办理') }}
              </span>
             <template v-if="record.executor=='0'">
              <span @click.stop="setAssignee(record)">
                  {{i18n('form.setExecutor','设置执行人') }}
              </span>
             </template>
          </span>

                </rx-grid>
            </rx-fit>
        </div>
    </rx-layout>
</template>


<script>
    import BpmtaskApi from '@/api/bpm/core/bpmTask'
    import {BaseList, RxLayout, RxFit, RxGrid, Dialog} from '@lowcode/jpaas-common-lib'
    import RxCategoryTreeeditor from "@/components/redxun/rx-category-treeeditor";
    import FlowUtil from "../js/FlowUtil";
    import {mapState} from 'vuex';
    import AppSearch from "@/views/modules/share/AppSearch";
    import RxSearchApp from "@/views/modules/share/rx-search-app";
    import instAndTaskShare from "@/views/modules/bpm/core/js/instAndTaskShare";
    export default {
        name: 'BpmTaskList',
        mixins: [BaseList, instAndTaskShare,FlowUtil,AppSearch],
        components: {
            RxLayout,
            RxFit,
            RxGrid,
            RxCategoryTreeeditor,
            RxSearchApp
        },
        computed: {
            ...mapState({
                // 所属应用
                allApps: state => state.appSetting ? state.appSetting.allApps : {}
            }),
        },
        data() {
            return {
                statusMap: {
                    "UNHANDLE": {color: 'red', text: this.i18n('form.waitToDo', '待办')},
                    "HANDLE": {color: 'green', text: this.i18n('form.processing', '处理中')},
                    "LOCKED": {color: 'orange', text: this.i18n('form.locked', '已锁定')},
                    "PENDING": {color: 'blue', text: this.i18n('form.pending', '已挂起')},
                },
                treeData: [],
                selTreeId: '',
                gridData: [],

                // 查询参数
                queryParam: {},

                // 表头
                columns: [
                    {
                        title: this.$ti18('rxList.index', '序号'),
                        type: 'indexColumn',
                        dataIndex: 'serial',
                        scopedSlots: {customRender: 'serial'},
                        width: 50
                    },
                    {
                        title: this.i18n('form.itemTitle', '事项标题'),
                        dataIndex: 'subject',
                        width: 200,
                        scopedSlots: {customRender: 'subject'},
                        ellipsis: false,

                    },
                    {
                        title: this.i18n('form.oddNumbers', '单号'),
                        dataIndex: 'billNo',
                        width: 200
                    },
                    {
                        title: this.i18n('form.approvalProcess', '审批环节'),
                        dataIndex: 'name',
                        width: 100
                    },

                    {
                        title: this.i18n('form.executor', '执行人'),
                        dataIndex: 'assignee',
                        scopedSlots: {customRender: 'assignee'},
                        width: 120
                    },
                    {
                        title: this.i18n('form.status', '状态'),
                        dataIndex: 'status',
                        scopedSlots: {customRender: 'status'},
                        width: 120

                    },
                    {
                        title: this.i18n('form.application', '所属应用'),
                        dataIndex: 'appId',
                        width: 140,
                        sortField: 'APP_ID_',
                        scopedSlots: {customRender: 'appId'}
                    },
                    {
                        title: this.i18n('form.sendtime', '发送时间'),
                        dataIndex: 'createTime',
                        width: 120

                    },
                    {
                        title: this.$ti18('rxList.action', '操作'),
                        dataIndex: 'action',
                        width: 60,
                        fixed: 'right',
                        scopedSlots: {customRender: 'action'}
                    }
                ],

                selectedRowKeys: [],
                selectedRows: [],
                owner: [],
                assignee: [],
                statisticConfig: {
                    type: "static_bpm",
                    appIdPrefix:'t.',
                    table: "BPM_TASK t LEFT JOIN BPM_DEF v ON t.DEF_ID_ = v.DEF_ID_",
                    field: "t.TREE_ID_",
                    whereConf: [{
                        name: "STATUS_",
                        alias: 't.STATUS_',
                        type: "string",
                        dateFormat: "",
                        op: "!=",
                        value: "COMPLETED"
                    }]
                },
                isBpmClient:true,
                readKey:"task.read",
                treePrefix:'t.',
                appPrefix:"t."
            }
        },
        filters: {},
        created() {
        },
        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "bpmTask", key);
            },
            createTimeChange(dateArray, dateStrings) {
                this.queryParam['Q_t.CREATE_TIME__D_GE'] = dateStrings[0];
                this.queryParam['Q_t.CREATE_TIME__D_LE'] = dateStrings[1];
            },
            handSelect(curRow) {
                this.loadDataBySelectTreeNode(curRow);
            },

            toggleAdvanced() {
                this.advanced = !this.advanced
            },
            onSelectChange(selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys
                this.selectedRows = selectedRows
            },
            handleTask(record) {
                this.openInst(record.appId, record.instId, record.taskId);
            },
            delByIds(ids) {
                let scopeThis = this
                this.$confirm({
                    title: this.$ti18('rxMsa.actionTips', '操作提示'),
                    content: this.$ti18('rxMsa.delInfo', '您确定需要删除选中的记录吗？'),
                    okText: this.$ti18('rxForm.ackBtn', '确认'),
                    cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                    onOk() {
                        BpmtaskApi.delByIds(ids.join(',')).then(res => {
                            if (res.success && res.code == 200) {
                                scopeThis.handleOk()
                            }
                            scopeThis.selectedRowKeys = []
                        })
                    },
                    onCancel() {
                    }
                })
            },
            toggleSearch() {
                this.showSearch = !this.showSearch
            },
            setAssignee(record) {
                const self = this;
                var conf = {curVm: self, data: {single: false}, widthHeight: ['1024px', '600px']};
                Dialog.openUserDialog(conf, function (self, users) {
                    if (users.length > 0) {
                        var userIds = [];
                        for (var i = 0; i < users.length; i++) {
                            userIds.push(users[i].userId);
                        }
                        BpmtaskApi.setAssignee(record, userIds).then(res => {
                            self.$refs.table.loadData();
                        });
                    }
                });
            },
            search() {
                this.$refs.table.loadData()
            },
            searchbarClose() {
                this.fitSearch = false;
            }
        },
        watch: {
            owner: function (val) {
                this.queryParam.Q_OWNER__S_EQ = val[0].id;
            },
            assignee: function (val) {
                this.queryParam.Q_ASSIGNEE__S_EQ = val[0].id;
            }
        }
    }
</script>
<style scoped>

</style>

